<template>
	<view class="apply-container">

		<!-- 用户信息卡片 -->
		<view class="user-card">
			<view class="user-main-info">
				<view class="user-avatar">
					<image :src="currentSignUser?.avatar || '/static/logo.png'" class="avatar-img" mode="aspectFill">
					</image>
				</view>
				<view class="user-info">
					<view class="user-name">{{ currentSignUser?.name || currentSignUser?.nickname || '用户' }}</view>
					<view class="user-gender">{{ currentSignUser?.gender === 0 ? '女' : currentSignUser?.gender === 1 ?
						'男' : '女' }} {{
							currentSignUser?.age || '28' }}岁</view>
				</view>
				<view class="contract-tag" @click="showMemberPicker">
					<text class="tag-text">切换签约人</text>
				</view>
			</view>

			<!-- 用户详细信息在卡片内 -->
			<view class="user-details-in-card">
				<view class="detail-row">
					<text class="detail-label">身份证号</text>
					<text class="detail-value">{{ currentSignUser?.IDnumber || '暂无' }}</text>
				</view>
				<view class="detail-row">
					<text class="detail-label">联系电话</text>
					<text class="detail-value">{{ currentSignUser?.phone || '暂无' }}</text>
				</view>
				<view class="detail-row">
					<text class="detail-label">家庭住址</text>
					<text class="detail-value">{{ currentSignUser?.address || '暂无' }}</text>
				</view>
			</view>
		</view>

		<!-- 签约信息列表 -->
		<view class="contract-info">
			<view class="info-item">
				<text class="info-label">签约机构</text>
				<text class="info-value">{{ selectedTeam.organizationId?.name }}</text>
			</view>

			<view class="info-item" @click="showTeamSelector">
				<text class="info-label">签约团队</text>
				<text class="info-value" :class="{ placeholder: !selectedTeam.name }">
					{{ selectedTeam.name }}
				</text>
				<text class="arrow">></text>
			</view>

			<view class="info-item" @click="showDoctorSelector" v-if="selectedTeam.name">
				<text class="info-label">签约医生</text>
				<text class="info-value" :class="{ placeholder: !selectedDoctor.name }">
					{{ selectedDoctor.name || '请选择签约医生' }}
				</text>
				<text class="arrow">></text>
			</view>

			<view class="info-item" @click="showServicePackSelector">
				<text class="info-label">服务包</text>
				<text class="info-value" :class="{ placeholder: !selectedServicePack.name }">
					{{ selectedServicePack.name || '请选择服务包' }}
				</text>
				<text class="arrow">></text>
			</view>

			<view class="info-item">
				<text class="info-label">签约周期</text>
				<text class="info-value">{{ selectedServicePack.period || '1年' }}</text>
			</view>

			<view class="info-item" @click="showDatePicker">
				<text class="info-label">生效日期</text>
				<text class="info-value" :class="{ placeholder: !effectiveDate }">
					{{ effectiveDate ? formatDate(effectiveDate) : '请选择生效日期' }}
				</text>
				<text class="arrow">></text>
			</view>

			<view class="info-item">
				<text class="info-label">费用</text>
				<text class="info-value price">¥{{ selectedServicePack.price || '0' }}</text>
			</view>
		</view>

		<!-- 备注输入 -->
		<view class="remark-section">
			<text class="remark-label">备注</text>
			<textarea class="remark-input" placeholder="请填写备注" v-model="remark" maxlength="200"></textarea>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-section">
			<button class="submit-btn" @click="submitContract">提交申请</button>
		</view>

		<!-- 团队选择弹窗 -->
		<view class="team-picker-overlay" v-if="showTeamPicker" @click="showTeamPicker = false">
			<view class="team-picker-content" @click.stop>
				<view class="picker-header">
					<text class="picker-title">请选择医生团队</text>
				</view>

				<view class="team-list">
					<view class="team-item" v-for="team in teamList" :key="team._id" @click="selectTeam(team)">
						<text class="team-name">{{ team.name }}</text>
					</view>
				</view>

				<view class="picker-footer">
					<button class="cancel-btn" @click="showTeamPicker = false">取消</button>
				</view>
			</view>
		</view>

		<!-- 医生选择弹窗 -->
		<view class="team-picker-overlay" v-if="showDoctorPicker" @click="showDoctorPicker = false">
			<view class="team-picker-content" @click.stop>
				<view class="picker-header">
					<text class="picker-title">请选择签约医生</text>
				</view>

				<view class="team-list">
					<view class="doctor-item" v-for="doctor in doctorList" :key="doctor._id"
						@click="selectDoctor(doctor)">
						<text class="doctor-name">{{ doctor.name }}</text>
						<text class="doctor-type">{{ doctor.type }}</text>
					</view>

					<!-- 如果没有医生，显示提示 -->
					<view class="empty-tip" v-if="doctorList.length === 0">
						<text>暂无可选医生</text>
					</view>
				</view>

				<view class="picker-footer">
					<button class="cancel-btn" @click="showDoctorPicker = false">取消</button>
				</view>
			</view>
		</view>

		<!-- 日期选择器 -->
		<view class="date-picker-overlay" v-if="showDateSelector" @click="showDateSelector = false">
			<view class="date-picker-content" @click.stop>
				<view class="picker-header">
					<text class="picker-cancel" @click="showDateSelector = false">取消</text>
					<text class="picker-title">选择生效日期</text>
					<text class="picker-confirm" @click="confirmDate">确定</text>
				</view>
				<picker-view class="date-picker-view" :value="pickerValue" @change="onDateChange">
					<picker-view-column>
						<view v-for="(year, index) in years" :key="index" class="picker-item">{{ year }}年</view>
					</picker-view-column>
					<picker-view-column>
						<view v-for="(month, index) in months" :key="index" class="picker-item">{{ month }}月</view>
					</picker-view-column>
					<picker-view-column>
						<view v-for="(day, index) in days" :key="index" class="picker-item">{{ day }}日</view>
					</picker-view-column>
				</picker-view>
			</view>
		</view>
	</view>

	<!-- 家庭成员选择器 -->
	<view v-if="showMemberSelector" class="member-selector-overlay" @click="cancelMemberSelect">
		<view class="member-selector-content" @click.stop>
			<view class="selector-header">
				<text class="selector-title">请选择签约人</text>
			</view>

			<scroll-view class="member-list" scroll-y>
				<view v-for="member in familyMembers" :key="member._id" class="member-item"
					:class="{ active: currentSignUser?._id === member._id }" @click="selectSignUser(member)">
					<view class="member-info">
						<image :src="member.avatar || '/static/logo.png'" class="member-avatar" mode="aspectFill">
						</image>
						<view class="member-details">
							<text class="member-name">{{ member.name }}</text>
							<text class="member-relation">{{ member.relationship }}</text>
						</view>
					</view>
					<view v-if="currentSignUser?._id === member._id" class="selected-icon">✓</view>
				</view>
			</scroll-view>

			<view class="selector-footer">
				<button class="cancel-btn" @click="cancelMemberSelect">取消</button>
			</view>
		</view>
	</view>

	<!-- 服务包选择弹窗 -->
	<view class="service-pack-overlay" v-if="showServicePackPicker" @click="showServicePackPicker = false">
		<view class="service-pack-content" @click.stop>
			<view class="selector-header">
				<text class="selector-title">请选择签约服务包</text>
			</view>

			<scroll-view scroll-y class="service-pack-list">
				<view class="service-pack-item" v-for="(pack, index) in servicePackList" :key="pack._id || index"
					@click="selectServicePack(pack)">
					<view class="pack-info">
						<text class="pack-name">{{ pack.name }}</text>
						<text class="pack-price">¥{{ pack.price }}</text>
					</view>
					<view v-if="selectedServicePack._id === pack._id" class="selected-icon">✓</view>
				</view>
			</scroll-view>

			<view class="selector-footer">
				<button class="cancel-btn" @click="cancelServicePackSelect">取消</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import {
	ref,
	onMounted
} from 'vue'
import {
	onLoad
} from '@dcloudio/uni-app'
import {
	getTeamApi,
	getDoctorDetailApi
} from '@/api/doctor.js'
import {
	addContractApi
} from '@/api/signs.js'
import {
	useUserStore
} from '@/store/user.js'
import {
	useContractStore
} from '@/store/contract.js'
import {
	searchMemberApi
} from '@/api/home-member.js'

// 用户状态管理
const userStore = useUserStore()
// 签约状态管理
const contractStore = useContractStore()

// 响应式数据
const userInfo = ref({})
const teamDetail = ref({})
const teamList = ref([])
const selectedTeam = ref({})
const selectedDoctor = ref({})
const doctorList = ref([])
const remark = ref('')
const organizationId = ref('')
const doctorId = ref('')
const teamId = ref('') // 添加团队ID参数
const showTeamPicker = ref(false)
const showDoctorPicker = ref(false)

// 家庭成员相关
const familyMembers = ref([]) // 家庭成员列表
const showMemberSelector = ref(false) // 是否显示成员选择器
const currentSignUser = ref(null) // 当前选中的签约人

// 服务包相关
const servicePackList = ref([]) // 服务包列表
const selectedServicePack = ref({}) // 选中的服务包
const showServicePackPicker = ref(false) // 是否显示服务包选择器

// 日期选择相关
const effectiveDate = ref('')
const showDateSelector = ref(false)
const pickerValue = ref([0, 0, 0])
const years = ref([])
const months = ref([])
const days = ref([])

// 获取用户信息
const getUserInfo = async () => {
	// 如果状态管理中已有用户信息，直接使用
	if (userStore.userInfo) {
		userInfo.value = userStore.userInfo
		currentSignUser.value = userStore.userInfo // 设置当前签约人为登录用户
	} else {
		// 否则从服务器获取
		await userStore.getUserInfoAction()
		userInfo.value = userStore.userInfo
		currentSignUser.value = userStore.userInfo // 设置当前签约人为登录用户
	}

	// 获取家庭成员
	await getFamilyMembers()
}

// 获取家庭成员列表
const getFamilyMembers = async () => {
	if (!userInfo.value._id) return

	const res = await searchMemberApi({
		ownId: userInfo.value._id
	})

	if (res.code === 200) {
		// 处理家庭成员数据，添加当前用户到列表首位
		const members = res.data.map(item => ({
			...item.otherId,
			relationship: item.relationship
		}))

		// 将当前用户添加到列表首位
		familyMembers.value = [
			{
				...userInfo.value,
				relationship: '本人'
			},
			...members
		]
	}
}

// 显示成员选择器
const showMemberPicker = () => {
	showMemberSelector.value = true
}

// 选择签约人
const selectSignUser = (member) => {
	currentSignUser.value = member
	showMemberSelector.value = false

	uni.showToast({
		title: `已切换为${member.name}签约`,
		icon: 'success'
	})
}

// 取消选择
const cancelMemberSelect = () => {
	showMemberSelector.value = false
}

// 显示服务包选择器
const showServicePackSelector = () => {
	if (servicePackList.value.length === 0) {
		uni.showToast({
			title: '暂无可选服务包',
			icon: 'none'
		})
		return
	}
	showServicePackPicker.value = true
}

// 选择服务包
const selectServicePack = (pack) => {
	selectedServicePack.value = pack
	showServicePackPicker.value = false

	uni.showToast({
		title: `已选择${pack.name}`,
		icon: 'success'
	})
}

// 取消服务包选择
const cancelServicePackSelect = () => {
	showServicePackPicker.value = false
}

// 获取团队列表
const getTeamList = async () => {
	const res = await getTeamApi({
		organizationId: organizationId.value,
		currentPage: 1,
		pageSize: 100,
		state: 1
	})

	if (res.code === 200) {
		teamList.value = res.data.rows

		// 优先根据团队ID选择团队，如果没有团队ID则根据医生ID选择
		if (teamId.value) {
			autoSelectTeamById()
		} else if (doctorId.value) {
			autoSelectTeamByDoctor()
		}
	} else {
		uni.showToast({
			title: res.message,
			icon: 'none'
		})
	}
}

// 根据医生ID自动选择团队
const autoSelectTeamByDoctor = () => {
	if (doctorId.value && teamList.value.length > 0) {
		// 在团队列表中查找包含该医生的团队
		let targetTeam = null
		let targetDoctor = null

		for (const team of teamList.value) {
			// 检查团队长是否是目标医生
			const leaderIdToCheck = team.leaderId?._id || team.leaderId
			if (leaderIdToCheck === doctorId.value) {
				targetTeam = team
				targetDoctor = {
					_id: leaderIdToCheck,
					name: team.leaderId?.name || '团队长',
					avatar: team.leaderId?.avatar,
					type: '全科医生'
				}
				break
			}

			// 检查团队成员中是否有目标医生
			if (team.memberIds && team.memberIds.length > 0) {
				const member = team.memberIds.find(member => {
					const memberId = typeof member === 'string' ? member : member._id
					return memberId === doctorId.value
				})

				if (member) {
					targetTeam = team
					targetDoctor = typeof member === 'string' ?
						{
							_id: member,
							name: '团队成员',
							type: '医生'
						} :
						{
							_id: member._id,
							name: member.name,
							avatar: member.avatar,
							phone: member.phone,
							type: member.roleId?.name || '医生'
						}
					break
				}
			}
		}

		if (targetTeam && targetDoctor) {
			// 验证机构ID是否一致
			const teamOrgId = targetTeam.organizationId?._id || targetTeam.organizationId
			if (teamOrgId && organizationId.value && teamOrgId !== organizationId.value) {
				// 使用团队的机构ID作为正确的机构ID
				organizationId.value = teamOrgId
			}

			// 设置选中的团队
			selectedTeam.value = targetTeam

			// 设置默认选中的医生
			selectedDoctor.value = targetDoctor

			// 构建医生列表
			buildDoctorList(targetTeam)

			// 获取团队详情
			getTeamDetail()
		}
	}
}

// 根据团队ID自动选择团队
const autoSelectTeamById = () => {
	if (teamId.value && teamList.value.length > 0) {
		// 在团队列表中查找指定的团队
		const targetTeam = teamList.value.find(team => team._id === teamId.value)

		if (targetTeam) {
			// 设置选中的团队
			selectedTeam.value = targetTeam

			// 根据医生ID选择医生，如果没有医生ID则选择团队长
			let targetDoctor = null

			if (doctorId.value) {
				// 检查团队长是否是目标医生
				const leaderIdToCheck = targetTeam.leaderId?._id || targetTeam.leaderId
				if (leaderIdToCheck === doctorId.value) {
					targetDoctor = {
						_id: leaderIdToCheck,
						name: targetTeam.leaderId?.name || '团队长',
						avatar: targetTeam.leaderId?.avatar,
						type: '全科医生'
					}
				} else if (targetTeam.memberIds && targetTeam.memberIds.length > 0) {
					// 在团队成员中查找目标医生
					const member = targetTeam.memberIds.find(member => {
						const memberId = typeof member === 'string' ? member : member._id
						return memberId === doctorId.value
					})

					if (member) {
						targetDoctor = typeof member === 'string' ?
							{
								_id: member,
								name: '团队成员',
								type: '医生'
							} :
							{
								_id: member._id,
								name: member.name,
								avatar: member.avatar,
								phone: member.phone,
								type: member.roleId?.name || '医生'
							}
					}
				}
			}

			// 如果没有找到指定医生，默认选择团队长
			if (!targetDoctor) {
				const leaderIdToCheck = targetTeam.leaderId?._id || targetTeam.leaderId
				targetDoctor = {
					_id: leaderIdToCheck,
					name: targetTeam.leaderId?.name || '团队长',
					avatar: targetTeam.leaderId?.avatar,
					type: '全科医生'
				}
			}

			// 设置默认选中的医生
			selectedDoctor.value = targetDoctor

			// 构建医生列表
			buildDoctorList(targetTeam)

			// 获取团队详情
			getTeamDetail()

			// 验证机构ID是否一致
			const teamOrgId = targetTeam.organizationId?._id || targetTeam.organizationId
			if (teamOrgId && organizationId.value && teamOrgId !== organizationId.value) {
				// 使用团队的机构ID作为正确的机构ID
				organizationId.value = teamOrgId
			}
		}
	}
}

// 获取团队详情
const getTeamDetail = async () => {
	const res = await getDoctorDetailApi({
		_id: selectedTeam.value._id
	})

	if (res.code === 200) {
		teamDetail.value = res.data

		// 设置服务包列表
		if (teamDetail.value.servicePackIds && teamDetail.value.servicePackIds.length > 0) {
			servicePackList.value = teamDetail.value.servicePackIds
			// 默认选择第一个服务包
			if (!selectedServicePack.value._id) {
				selectedServicePack.value = teamDetail.value.servicePackIds[0]
			}
		}

		// 使用最新的团队详情重新构建医生列表
		if (teamDetail.value.memberIds) {
			buildDoctorList(teamDetail.value)

			// 如果有医生ID，重新设置默认选中的医生（使用完整的团队详情数据）
			if (doctorId.value) {
				updateSelectedDoctorFromTeamDetail()
			}
		}
	} else {
		uni.showToast({
			title: res.message,
			icon: 'none'
		})
	}
}

// 使用团队详情更新选中的医生信息
const updateSelectedDoctorFromTeamDetail = () => {
	if (!doctorId.value || !teamDetail.value) return

	// 检查团队长
	if (teamDetail.value.leaderId && teamDetail.value.leaderId._id === doctorId.value) {
		selectedDoctor.value = {
			_id: teamDetail.value.leaderId._id,
			name: teamDetail.value.leaderId.name,
			avatar: teamDetail.value.leaderId.avatar,
			phone: teamDetail.value.leaderId.phone,
			type: '全科医生'
		}
		return
	}

	// 检查团队成员
	if (teamDetail.value.memberIds && teamDetail.value.memberIds.length > 0) {
		const member = teamDetail.value.memberIds.find(member =>
			member && member._id === doctorId.value
		)

		if (member) {
			selectedDoctor.value = {
				_id: member._id,
				name: member.name,  // 使用团队详情中的真实姓名
				avatar: member.avatar,
				phone: member.phone,
				type: member.roleId?.name || '医生'
			}
		}
	}
}

// 显示团队选择器
const showTeamSelector = () => {
	showTeamPicker.value = true
}

// 显示医生选择器
const showDoctorSelector = () => {
	// 确保有选中的团队
	if (selectedTeam.value && selectedTeam.value._id) {
		// 优先使用团队详情数据，如果没有则使用选中的团队数据
		const teamData = teamDetail.value && teamDetail.value._id ? teamDetail.value : selectedTeam.value

		// 重新构建当前团队的医生列表
		buildDoctorList(teamData)

		if (doctorList.value.length === 0) {
			uni.showToast({
				title: '该团队暂无可选医生',
				icon: 'none'
			})
			return
		}

		showDoctorPicker.value = true
	} else {
		uni.showToast({
			title: '请先选择团队',
			icon: 'none'
		})
	}
}

// 构建医生列表
const buildDoctorList = (team) => {
	doctorList.value = []

	// 获取团队长ID（用于去重）
	const leaderId = typeof team.leaderId === 'string' ? team.leaderId : team.leaderId?._id

	// 添加团队长
	if (team.leaderId) {
		const leader = typeof team.leaderId === 'string' ?
			{
				_id: team.leaderId,
				name: '团队长',
				type: '全科医生'
			} :
			{
				_id: team.leaderId._id,
				name: team.leaderId.name, // 使用团队长的真实姓名
				type: '全科医生',
				avatar: team.leaderId.avatar,
				phone: team.leaderId.phone
			}

		doctorList.value.push(leader)
	}

	// 添加团队成员
	if (team.memberIds && team.memberIds.length > 0) {
		team.memberIds.forEach(member => {
			// 检查成员是否是对象并且有name属性
			if (typeof member === 'object' && member !== null) {
				// 避免重复添加团队长
				if (member._id !== leaderId) {
					const doctorInfo = {
						_id: member._id,
						name: member.name, // 直接使用成员的name属性
						type: member.roleId?.name || '医生',
						avatar: member.avatar,
						phone: member.phone
					}

					doctorList.value.push(doctorInfo)
				}
			} else if (typeof member === 'string') {
				// 如果成员是字符串ID，则显示为"团队成员"
				if (member !== leaderId) {
					doctorList.value.push({
						_id: member,
						name: '团队成员',
						type: '医生'
					})
				}
			}
		})
	}
}

// 选择医生
const selectDoctor = (doctor) => {
	selectedDoctor.value = doctor
	showDoctorPicker.value = false
}

// 日期选择相关方法
const initDatePicker = () => {
	const currentYear = new Date().getFullYear()
	const currentMonth = new Date().getMonth() + 1
	const currentDay = new Date().getDate()

	// 生成年份数组（当前年份到未来5年）
	years.value = []
	for (let i = currentYear; i <= currentYear + 5; i++) {
		years.value.push(i)
	}

	// 生成月份数组
	months.value = []
	for (let i = 1; i <= 12; i++) {
		months.value.push(i.toString().padStart(2, '0'))
	}

	// 生成日期数组
	updateDays(currentYear, currentMonth)

	// 设置默认选中今天
	pickerValue.value = [0, currentMonth - 1, currentDay - 1]
}

const updateDays = (year, month) => {
	const daysInMonth = new Date(year, month, 0).getDate()
	days.value = []
	for (let i = 1; i <= daysInMonth; i++) {
		days.value.push(i.toString().padStart(2, '0'))
	}
}

const showDatePicker = () => {
	initDatePicker()
	showDateSelector.value = true
}

const onDateChange = (e) => {
	pickerValue.value = e.detail.value
	const selectedYear = years.value[e.detail.value[0]]
	const selectedMonth = parseInt(months.value[e.detail.value[1]])

	// 更新日期数组
	updateDays(selectedYear, selectedMonth)
}

const confirmDate = () => {
	const selectedYear = years.value[pickerValue.value[0]]
	const selectedMonth = months.value[pickerValue.value[1]]
	const selectedDay = days.value[pickerValue.value[2]]

	effectiveDate.value = `${selectedYear}-${selectedMonth}-${selectedDay}`
	showDateSelector.value = false
}

const formatDate = (dateStr) => {
	if (!dateStr) return ''
	const [year, month, day] = dateStr.split('-')
	return `${year}年${month}月${day}日`
}

// 选择团队
const selectTeam = (team) => {
	selectedTeam.value = team
	showTeamPicker.value = false

	// 构建医生列表
	buildDoctorList(team)

	// 默认选择团队长作为签约医生
	if (team.leaderId) {
		const leader = typeof team.leaderId === 'string' ?
			{
				_id: team.leaderId,
				name: '团队长',
				type: '全科医生'
			} :
			{
				_id: team.leaderId._id,
				name: team.leaderId.name,
				type: '全科医生',
				avatar: team.leaderId.avatar
			}
		selectedDoctor.value = leader
	} else {
		selectedDoctor.value = {}
	}

	// 选择团队后获取团队详情
	getTeamDetail()
}

// 提交签约申请
const submitContract = async () => {
	// 验证必填信息
	if (!selectedTeam.value._id) {
		uni.showToast({
			title: '请选择签约团队',
			icon: 'none'
		})
		return
	}

	if (!selectedDoctor.value._id) {
		uni.showToast({
			title: '请选择签约医生',
			icon: 'none'
		})
		return
	}

	if (!effectiveDate.value) {
		uni.showToast({
			title: '请选择生效日期',
			icon: 'none'
		})
		return
	}

	if (!selectedServicePack.value._id) {
		uni.showToast({
			title: '请选择服务包',
			icon: 'none'
		})
		return
	}

	uni.showModal({
		title: '确认提交',
		content: '确定要提交签约申请吗？',
		success: async (res) => {
			if (res.confirm) {
				// 显示加载中
				uni.showLoading({
					title: '提交中...'
				})

				// 准备API请求数据，使用当前选中的签约人信息
				const contractData = {
					residentId: currentSignUser.value?._id || userStore.userInfo?._id,
					organizationId: selectedTeam.value.organizationId?._id || organizationId.value,
					teamId: selectedTeam.value._id,
					doctorId: selectedDoctor.value._id,
					servicePackId: selectedServicePack.value._id,
					type: currentSignUser.value?._id === userStore.userInfo?._id ? '首次签约' : '家庭成员签约',
					remark: remark.value || '无',
					applyTime: new Date().toLocaleString('zh-CN', {
						year: 'numeric',
						month: '2-digit',
						day: '2-digit',
						hour: '2-digit',
						minute: '2-digit'
					}).replace(/\//g, '-'),
					effectiveDate: effectiveDate.value // 使用用户选择的生效日期
				}

				// 调用API提交签约申请
				const response = await addContractApi(contractData)

				uni.hideLoading()

				if (response.code === 200) {
					// 提交成功，获取签约记录ID
					const contractId = response.data?._id

					// 保存签约申请详情到状态机
					const applicationDetail = {
						contractId: contractId,
						applicant: currentSignUser.value?.name || userStore.userInfo?.name,
						applicantId: currentSignUser.value?._id || userStore.userInfo?._id,
						doctorName: selectedDoctor.value.name,
						doctorId: selectedDoctor.value._id,
						doctorAvatar: selectedDoctor.value.avatar,
						doctorTitle: selectedDoctor.value.title || '全科医生',
						teamName: selectedTeam.value.name,
						teamId: selectedTeam.value._id,
						organizationName: selectedTeam.value.organizationId?.name,
						organizationId: selectedTeam.value.organizationId?._id || organizationId.value,
						servicePackageName: selectedServicePack.value.name,
						servicePackageId: selectedServicePack.value._id,
						servicePackagePrice: selectedServicePack.value.price,
						servicePackagePeriod: selectedServicePack.value.period,
						effectiveDate: effectiveDate.value,
						remark: remark.value || '无',
						contractType: currentSignUser.value?._id === userStore.userInfo?._id ? '首次签约' : '家庭成员签约',
						state: 1, // 待审核状态
						submitTime: new Date().toLocaleString('zh-CN')
					}

					// 保存到状态机
					contractStore.saveContractApplication(applicationDetail)

					// 只传递签约记录ID，其他信息通过API获取
					const progressParams = `contractId=${contractId}`

					uni.redirectTo({
						url: `/homepackge/pages/success/success?title=${encodeURIComponent('提交申请成功，等待医生审核')}&description=${encodeURIComponent('您的签约申请已提交，正在等待医生审核')}
						&primaryText=${encodeURIComponent('查看签约进度')}&secondaryText=${encodeURIComponent('返回首页')}
						&primaryUrl=${encodeURIComponent(`/homepackge/pages/contract-progress/contract-progress?${progressParams}`)}`
					})
				} else {
					uni.showToast({
						title: response.message,
						icon: 'none'
					})
				}
			}
		}
	})
}

// 页面加载时接收参数
onLoad((options) => {
	if (options.organizationId) {
		organizationId.value = options.organizationId
	}
	if (options.doctorId) {
		doctorId.value = options.doctorId
	}
	if (options.teamId) {
		teamId.value = options.teamId
	}

	// 检查是否有签约详情（续约场景）
	if (contractStore.hasContractDetail && contractStore.contractInfo && !options.organizationId && !options.doctorId && !options.teamId) {
		// 只有在没有页面参数且有签约信息的情况下才使用签约状态数据
		const contractInfo = contractStore.contractInfo
		organizationId.value = contractInfo.organizationId?._id || ''
		doctorId.value = contractInfo.doctorId?._id || ''
		teamId.value = contractInfo.teamId?._id || ''

		// 设置选中的团队和医生信息
		selectedTeam.value = {
			_id: contractInfo.teamId?._id || '',
			name: contractInfo.teamId?.name || '',
			organizationId: { name: contractInfo.organizationId?.name || '' }
		}
		selectedDoctor.value = {
			_id: contractInfo.doctorId?._id || '',
			name: contractInfo.doctorId?.name || ''
		}

		// 设置备注为续约
		remark.value = '申请续约'
	} else if (contractStore.hasContractDetail && contractStore.contractInfo) {
		// 如果有页面参数，优先使用页面参数，只设置备注
		remark.value = '申请续约'
	}
})

// 页面挂载后获取数据
onMounted(async () => {
	uni.showLoading({
		title: '加载中...'
	})

	// 并行获取用户信息和团队列表
	await Promise.all([
		getUserInfo(),
		organizationId.value ? getTeamList() : Promise.resolve()
	])

	uni.hideLoading()
})
</script>

<style scoped>
.apply-container {
	background-color: #f5f5f5;
	min-height: 100vh;
}

.nav-bar {
	background-color: #fff;
	height: 88rpx;
	display: flex;
	align-items: center;
	position: relative;
	border-bottom: 1rpx solid #eee;
}

.nav-back {
	position: absolute;
	left: 20rpx;
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.back-icon {
	font-size: 36rpx;
	color: #333;
}

.nav-title {
	flex: 1;
	text-align: center;
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.user-card {
	background: #2983F8;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;
	position: relative;
}

.user-main-info {
	display: flex;
	align-items: center;
	margin-bottom: 30rpx;
}

.user-avatar {
	width: 100rpx;
	height: 100rpx;
	border-radius: 20%;
	overflow: hidden;
	margin-right: 24rpx;
}

.avatar-img {
	width: 100%;
	height: 100%;
}

.user-info {
	flex: 1;
}

.user-name {
	font-size: 36rpx;
	font-weight: 500;
	color: #fff;
	margin-bottom: 8rpx;
}

.user-gender {
	font-size: 28rpx;
	color: rgba(255, 255, 255, 0.8);
}

.contract-tag {
	background-color: rgba(255, 255, 255, 0.2);
	border-radius: 20rpx;
	padding: 8rpx 16rpx;
}

.tag-text {
	font-size: 24rpx;
	color: #fff;
}

.user-details-in-card .detail-row {
	height: 60rpx;
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
}

.user-details-in-card .detail-row:last-child {
	margin-bottom: 0;
}

.user-details-in-card .detail-label {
	width: 140rpx;
	font-size: 26rpx;
	color: rgba(255, 255, 255, 0.8);
}

.user-details-in-card .detail-value {
	flex: 1;
	font-size: 26rpx;
	color: #fff;
}

.contract-info {
	background-color: #fff;
	margin: 0 20rpx 20rpx 20rpx;
	border-radius: 12rpx;
	padding: 0 30rpx;
}

.info-item {
	height: 88rpx;
	display: flex;
	align-items: center;
	border-bottom: 1rpx solid #f0f0f0;
}

.info-item:last-child {
	border-bottom: none;
}

.info-label {
	width: 140rpx;
	font-size: 28rpx;
	color: #666;
}

.info-value {
	flex: 1;
	font-size: 28rpx;
	color: #333;
}

.price {
	color: #ff4757;
	font-weight: 500;
}

.arrow {
	font-size: 24rpx;
	color: #ccc;
}

.remark-section {
	background-color: #fff;
	margin: 0 20rpx 20rpx 20rpx;
	border-radius: 12rpx;
	padding: 30rpx;
}

.remark-label {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 20rpx;
	display: block;
}

.remark-input {
	width: 100%;
	min-height: 120rpx;
	font-size: 28rpx;
	color: #333;
	background-color: #f8f8f8;
	border-radius: 8rpx;
	padding: 20rpx;
	box-sizing: border-box;
}

.submit-section {
	padding: 40rpx 20rpx;
}

.submit-btn {
	width: 100%;
	height: 88rpx;
	background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
	color: #fff;
	border: none;
	border-radius: 12rpx;
	font-size: 32rpx;
	font-weight: 500;
}

.placeholder {
	color: #999 !important;
}

/* 团队选择弹窗样式 */
.team-picker-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: flex-end;
	z-index: 1000;
}

.team-picker-content {
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	width: 100%;
	max-height: 80vh;
	overflow: hidden;
}

.picker-header {
	padding: 30rpx;
	text-align: center;
	border-bottom: 1rpx solid #f0f0f0;
}

.picker-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.team-list {
	max-height: 60vh;
	overflow-y: auto;
}

.team-list .team-item {
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
	text-align: center;
}

.team-list .team-item:last-child {
	border-bottom: none;
}

.team-name {
	font-size: 32rpx;
	color: #4A90E2;
}

.picker-footer {
	padding: 20rpx 30rpx 40rpx;
	border-top: 10rpx solid #f0f0f0;
}

.cancel-btn {
	width: 100%;
	height: 80rpx;
	background-color: #f5f5f5;
	color: #666;
	border: none;
	border-radius: 12rpx;
	font-size: 28rpx;
}

/* 医生选择弹窗样式 */
.doctor-item {
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.doctor-item:last-child {
	border-bottom: none;
}

.doctor-name {
	font-size: 32rpx;
	color: #4A90E2;
	margin-bottom: 8rpx;
}

.doctor-type {
	font-size: 24rpx;
	color: #999;
}

/* 日期选择器样式 */
.date-picker-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: flex-end;
	z-index: 1000;
}

.date-picker-content {
	width: 100%;
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	padding-bottom: env(safe-area-inset-bottom);
}

.date-picker-content .picker-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx;
	border-bottom: 1px solid #f0f0f0;
}

.picker-cancel,
.picker-confirm {
	font-size: 32rpx;
	color: #4A90E2;
}

.date-picker-content .picker-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.date-picker-view {
	height: 400rpx;
}

.picker-item {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 80rpx;
	font-size: 32rpx;
	color: #333;
}

/* 家庭成员选择器样式 */
.member-selector-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: flex-end;
	z-index: 1000;
}

.member-selector-content {
	width: 100%;
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	padding-bottom: env(safe-area-inset-bottom);
	max-height: 80vh;
}

.selector-header {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #eee;
}

.selector-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.member-list {
	max-height: 500rpx;
	padding: 0 30rpx;
}

.member-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
}

.member-item:last-child {
	border-bottom: none;
}

.member-item.active {
	background-color: #f0f8ff;
}

.member-info {
	display: flex;
	align-items: center;
	flex: 1;
}

.member-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}

.member-details {
	display: flex;
	flex-direction: column;
}

.member-name {
	font-size: 32rpx;
	color: #333;
	margin-bottom: 8rpx;
}

.member-relation {
	font-size: 24rpx;
	color: #4A90E2;
}

.selected-icon {
	font-size: 32rpx;
	color: #4A90E2;
	font-weight: bold;
}

.selector-footer {
	padding: 30rpx;
	border-top: 1rpx solid #eee;
}

.cancel-btn {
	width: 100%;
	height: 80rpx;
	background-color: #f5f5f5;
	color: #666;
	border: none;
	border-radius: 10rpx;
	font-size: 32rpx;
}

/* 服务包选择弹窗样式 */
.service-pack-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: flex-end;
	z-index: 1000;
}

.service-pack-content {
	width: 100%;
	max-height: 70vh;
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	display: flex;
	flex-direction: column;
}

.service-pack-list {
	flex: 1;
	max-height: 50vh;
}

.service-pack-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.service-pack-item:active {
	background-color: #f8f8f8;
}

.pack-info {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.pack-name {
	font-size: 32rpx;
	color: #333;
	margin-bottom: 8rpx;
}

.pack-price {
	font-size: 28rpx;
	color: #4A90E2;
	font-weight: bold;
}
</style>